// 响应拦截器
import nProgress from 'nprogress'
import 'nprogress/nprogress.css'
import router from '@/router'
import store from '@/store'

const whiteList = ['/login', '/404']

// 前置守卫
router.beforeEach(async(to, from, next) => {
  nProgress.start()
  const token = store.getters.token
  if (token) {
    //   判断是不是去登录页
    if (to.path === '/login') {
      next('/')// 引导到首页
      nProgress.done()
    } else {
      if (!store.state.user.userInfo.userId) {
        const { roles } = await store.dispatch('user/getUserInfo')
        console.log(roles.menus)
        const otherRoute = await store.dispatch('permission/filterRoute', roles.menus)
        console.log(otherRoute)
        router.addRoutes([
          ...otherRoute,
          { path: '*', redirect: '/404', hidden: true }
        ])
        next({
          ...to,
          replace: true
        })
        return
      }
      next()// 放行
    }
  } else {
    if (whiteList.includes(to.path)) {
      next()
    } else {
      next('/login')
      nProgress.done()
    }
  }
})

// 后置守卫
router.afterEach((to, form) => {
  nProgress.done()
})
